package logic

import (
	"context"
	"errors"
	"refister-kit/model/cache"
	"refister-kit/model/mysql"
	"refister-kit/pkg"

	"refister-kit/registerrpc/internal/svc"
	"refister-kit/registerrpc/registerrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *registerrpc.LoginRequest) (*registerrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前用户不存在，请更换")
	}

	if user.Password != pkg.MD5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	result, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Account).Result()
	if result != in.Captcha {
		return nil, errors.New("验证码错误，请重新输入")
	}

	return &registerrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
